/**
 * 28/ago/2012 - fabio.melillo@gmail.com
 */
package org.unisannio.util;

import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.BufferedReader;
import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLConnection;

import android.util.Log;

/**
 * @author Fabio Melillo
 * 
 */
public class TransferManager {

	public static int DOWNLOAD_BUFFER_SIZE = 1024;
	public static String ImageServerIP="192.168.1.5";
	public static String ImageServerPORT="8080";
	public static String partialURIUpload="/WebSchool/Upload";
	public static String partialURIDownload="/swap/";
	
	public static String getImageServerIP() {
		return ImageServerIP;
	}

	public static void setImageServerIP(String imageServerIP) {
		ImageServerIP = imageServerIP;
	}

	public static String getImageServerPORT() {
		return ImageServerPORT;
	}

	public static void setImageServerPORT(String imageServerPORT) {
		ImageServerPORT = imageServerPORT;
	}

	public static String upLoad2Server(String sourceFileUri) {
		String upLoadServerUri = "http://"+ImageServerIP+":"+ImageServerPORT+partialURIUpload;
		// String [] string = sourceFileUri;
		String fileName = sourceFileUri;
		String remoteFileName = null;
		int serverResponseCode = 0;

		HttpURLConnection conn = null;
		DataOutputStream dos = null;
		DataInputStream inStream = null;
		String lineEnd = "\r\n";
		String twoHyphens = "--";
		String boundary = "*****";
		int bytesRead, bytesAvailable, bufferSize;
		byte[] buffer;
		int maxBufferSize = 1 * 1024 * 1024;
		String responseFromServer = "";

		File sourceFile = new File(sourceFileUri);
		if (!sourceFile.isFile()) {
			Log.e("Android", "Source File Does not exist");
			return null;
		}
		try { // open a URL connection to the Servlet
			FileInputStream fileInputStream = new FileInputStream(sourceFile);
			URL url = new URL(upLoadServerUri);
			conn = (HttpURLConnection) url.openConnection(); // Open a HTTP
																// connection to
																// the URL
			conn.setDoInput(true); // Allow Inputs
			conn.setDoOutput(true); // Allow Outputs
			conn.setUseCaches(false); // Don't use a Cached Copy
			conn.setRequestMethod("POST");
			conn.setRequestProperty("Connection", "Keep-Alive");
			conn.setRequestProperty("ENCTYPE", "multipart/form-data");
			conn.setRequestProperty("Content-Type",
					"multipart/form-data;boundary=" + boundary);
			conn.setRequestProperty("uploaded_file", fileName);
			dos = new DataOutputStream(conn.getOutputStream());

			// dos.writeBytes(twoHyphens + boundary + lineEnd);
			// dos.writeBytes("Content-Disposition: form-data; name=\"uploaded_file\";filename=\""+
			// fileName + "\"" + lineEnd);
			// dos.writeBytes(lineEnd);

			bytesAvailable = fileInputStream.available(); // create a buffer of
															// maximum size
			Log.i("Android", "Initial .available : " + bytesAvailable);

			bufferSize = Math.min(bytesAvailable, maxBufferSize);
			buffer = new byte[bufferSize];

			// read file and write it into form...
			bytesRead = fileInputStream.read(buffer, 0, bufferSize);

			while (bytesRead > 0) {
				dos.write(buffer, 0, bufferSize);
				bytesAvailable = fileInputStream.available();
				bufferSize = Math.min(bytesAvailable, maxBufferSize);
				bytesRead = fileInputStream.read(buffer, 0, bufferSize);
			}

			// send multipart form data necesssary after file data...
			// dos.writeBytes(lineEnd);
			// dos.writeBytes(twoHyphens + boundary + twoHyphens + lineEnd);

			// Responses from the server (code and message)
			serverResponseCode = conn.getResponseCode();
			responseFromServer = conn.getResponseMessage();

			Log.i("Upload file to server", "HTTP Response is : "
					+ responseFromServer + ": " + serverResponseCode);
			// close streams
			Log.i("Upload file to server", fileName + " File is written");
			fileInputStream.close();
			dos.flush();
			dos.close();
		} catch (MalformedURLException ex) {
			ex.printStackTrace();
			Log.e("Upload file to server", "error: " + ex.getMessage(), ex);
		} catch (Exception e) {
			e.printStackTrace();
		}
		// this block will give the response of upload link
		try {
			BufferedReader rd = new BufferedReader(new InputStreamReader(
					conn.getInputStream()));
			String temp;
			while ((temp = rd.readLine()) != null) {
				Log.i("Servlet", "FileName: " + temp);
				remoteFileName = temp;
			}
			rd.close();
		} catch (IOException ioex) {
			Log.e("Servlet", "error: " + ioex.getMessage(), ioex);
		}
		return remoteFileName;

	} // end upLoad2Server

	public static String downloadFromServer(String imageUrl, String localPath) {
		try {
			URL url = new URL("http://"+ImageServerIP+":"+ImageServerPORT+partialURIDownload+imageUrl);
			Log.i("Download from url:",url.toString());
			URLConnection conn = url.openConnection();
			conn.setUseCaches(false);
			int fileSize = conn.getContentLength();

//			// get the filename
//			int lastSlash = url.toString().lastIndexOf('/');
//			String fileName = "file.jpg";
//			if (lastSlash >= 0) {
//				fileName = url.toString().substring(lastSlash + 1);
//			}
//			if (fileName.equals("")) {
//				fileName = "file.jpg";
//			}

			// notify download start
			int fileSizeInKB = fileSize / 1024;

			// start download
			BufferedInputStream inStream = new BufferedInputStream(
					conn.getInputStream());
			// File outFile = new File(Environment.getExternalStorageDirectory()
			// + "/" + fileName);
			File outFile = new File(localPath);
			if(outFile.isDirectory()){
				outFile=new File(localPath + "/" + imageUrl);
			}
			FileOutputStream fileStream = new FileOutputStream(outFile);
			BufferedOutputStream outStream = new BufferedOutputStream(
					fileStream, DOWNLOAD_BUFFER_SIZE);
			byte[] data = new byte[DOWNLOAD_BUFFER_SIZE];
			int bytesRead = 0, totalRead = 0;
			while ((bytesRead = inStream.read(data, 0, data.length)) >= 0) {
				outStream.write(data, 0, bytesRead);

				// update progress bar
				totalRead += bytesRead;
				int totalReadInKB = totalRead / 1024;
			}

			outStream.close();
			fileStream.close();
			inStream.close();

			return outFile.getAbsolutePath();

		} catch (MalformedURLException e) {
			System.err.println(e);
		} catch (FileNotFoundException e) {
			System.err.println(e);
		} catch (Exception e) {
			System.err.println(e);
		}
		return null;
	}

	

}
